using System.Collections.Generic;
using System.Configuration;
using System.Reflection;

namespace Mistral.Configuration
{
	public class ConfigurationUtils
	{
		public static bool ConfigHasKey( string key )
		{
			Assembly assembly = Assembly.GetEntryAssembly();
			System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration( assembly.Location );
			List<string> keys = new List<string>( configuration.AppSettings.Settings.AllKeys );
			for ( int i = 0; i < keys.Count; i++ )
			{
				keys[i] = keys[i].ToLower();
			}
			return keys.Contains( key.ToLower() );
		}

		public static void SetConfigAppSettings( string key, string value, bool bSave )
		{
			System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration( Assembly.GetExecutingAssembly().Location );
			SetConfigAppSettings( configuration, key, value, bSave );
		}

		public static void SetConfigAppSettings( System.Configuration.Configuration configuration, string key, string value, bool bSave )
		{
			List<string> keys = new List<string>( configuration.AppSettings.Settings.AllKeys );
			for( int i = 0; i < keys.Count; i++ )
			{
				keys[i] = keys[i].ToLower();
			}
			if( keys.Contains( key.ToLower() ) )
			{
				configuration.AppSettings.Settings[key].Value = value;
			}
			else
			{
				configuration.AppSettings.Settings.Add( key, value );
			}

			if( bSave )
				configuration.Save();
		}
	}
}
